import React, { useMemo, useCallback } from 'react';
import { Link } from 'react-router-dom';
import dayJs from 'dayjs';
import ClassNames from 'classnames';
import { usePrevious, useSetState, useUpdateEffect } from 'ahooks';
import { empty, paddingZero, add } from '@/common/utils';
import { enumBallType, enumFootballMatchStatus, enumBasketballMatchStatus } from '@/common/enum';
import Image from '@/components/Image';
import RenderJudge from '@/components/RenderJudge';
import PlayLoading from '@/components/PlayLoading';
// import { scoreSmallStatusFormat, secondFormatter } from '@/common/format';
import DefaultUserImage from '@/assets/images/default_user_image.png';
// import { smallStatusFormatter } from '../utils/common';

import styles from '../style/ScoreRow.scss';

const ScoreRow = ({ data, isBasketball, isFootball, defaultMatchImage }) => {
  const {
    startTime,
    matchType,
    eventName,
    homeTeamName,
    awayTeamName,
    homeTeamLogo,
    awayTeamLogo,
    preList,
    status,
    // smallState,
    // gameTime,
    score,
    // currentRound,
    homeTeamScore, // 主队得分
    awayTeamScore, // 客队得分
    teeTime,
    surplusTime,
    isLive,
    homeTeamRed,
    homeTeamYellow,
    awayTeamRed,
    awayTeamYellow,
  } = data;

  // 主/客比分变动指示效果
  const [visibleScorePoint, setVisibleScorePoint] = useSetState({ home: false, away: false });

  const { homeTeamCurrentScore, awayTeamCurrentScore } = score;
  // 上一次主队的分数
  const preHomeTeamCurrentScore = usePrevious(homeTeamCurrentScore || 0);
  // 上一次客队的分数
  const preAwayTeamCurrentScore = usePrevious(awayTeamCurrentScore || 0);

  useUpdateEffect(() => {
    // 主队分数变化增加三角形标识
    if (homeTeamCurrentScore > preHomeTeamCurrentScore) {
      setVisibleScorePoint({ home: true, away: false });
    }
    // 客队分数变化增加三角形标识
    if (awayTeamCurrentScore > preAwayTeamCurrentScore) {
      setVisibleScorePoint({ home: false, away: true });
    }
  }, [homeTeamCurrentScore, awayTeamCurrentScore]);

  // 小状态格式化
  // const smallStatusText = useMemo(() => {
  //   if (isFootball) {
  //     const statusCode = Number(smallState);
  //     const { label, disable } = scoreSmallStatusFormat(statusCode);
  //     if (disable || statusCode === 100) return label;

  //     let ret = gameTime || 1;
  //     if (statusCode === 20 || statusCode === 21 || statusCode === 22) {
  //       ret = '加';
  //     } else if (statusCode === 25) {
  //       ret = '点';
  //     } else if (statusCode === 31) {
  //       ret = '中';
  //     } else if (gameTime) {
  //       const timeCeil = Math.ceil(gameTime / 60);
  //       if (timeCeil) ret = timeCeil;
  //       if (status === 2) {
  //         if (statusCode === 1 && timeCeil > 45) ret = '45+';
  //         if (statusCode === 2 && timeCeil > 90) ret = '90+';
  //       }
  //     }
  //     return ret;
  //   }
  //   // 篮球
  //   if (isBasketball) {
  //     let resultText = smallStatusFormatter(smallState, eventName === 'NCAA');
  //     if (gameTime) {
  //       resultText = `${resultText} ${secondFormatter(gameTime, 'mm:ss')}`;
  //     }

  //     return resultText;
  //   }
  //   return null;
  // }, [matchType, status, smallState, eventName, gameTime]);

  // // 获取比分值 1：未开始，2：进行中，3：已结束
  // const getScoreHandle = (v) => {
  //   const defVal = status === 1 ? '-' : 0;

  //   return v || defVal;
  // };

  // 主、客轮次计算
  // const { homeTeamRoundsList, awayTeamRoundsList } = useMemo(() => {
  //   if (!isBasketball) {
  //     return {
  //       homeTeamRoundsList: [],
  //       awayTeamRoundsList: [],
  //     };
  //   }
  //   const {
  //     homeTeamScoredInTheFirstQuarter, // 主队第一节得分	2
  //     awayTeamScoredInTheFirstQuarter, // 客队第一节得分	3
  //     homeTeamScoredTheSecondQuarter, // 主队第二节得分	4
  //     awayTeamScoredTheSecondQuarter, // 客队第二节得分	5
  //     homeTeamScoreInTheThirdQuarter, // 主队第三节得分	6
  //     awayTeamScoredTheThirdQuarter, // 客队第三节得分	7
  //     homeTeamScoredTheFourthQuarter, // 主队第四节得分	8
  //     awayTeamScoredInTheFourthQuarter, // 客队第四节得分	9
  //     homeTeamOvertimeScore, // 主队加时得分	10
  //     awayTeamOvertimeScore, // 客队加时得分	11
  //   } = score;

  //   const isNcaaLeague = eventName === 'NCAA';

  //   let homeListFlag = [homeTeamScoredInTheFirstQuarter, homeTeamScoredTheSecondQuarter, homeTeamScoreInTheThirdQuarter, homeTeamScoredTheFourthQuarter, homeTeamOvertimeScore];
  //   let awayListFlag = [awayTeamScoredInTheFirstQuarter, awayTeamScoredTheSecondQuarter, awayTeamScoredTheThirdQuarter, awayTeamScoredInTheFourthQuarter, awayTeamOvertimeScore];

  //   if (isNcaaLeague) {
  //     homeListFlag = [homeTeamScoredInTheFirstQuarter, homeTeamScoreInTheThirdQuarter, homeTeamOvertimeScore];
  //   }

  //   if (isNcaaLeague) {
  //     awayListFlag = [awayTeamScoredInTheFirstQuarter, awayTeamScoredTheThirdQuarter, awayTeamOvertimeScore];
  //   }

  //   homeListFlag = homeListFlag.filter((row) => row !== null);
  //   awayListFlag = awayListFlag.filter((row) => row !== null);

  //   let maxListLength = Math.max(homeListFlag.length, awayListFlag.length);
  //   if (isNcaaLeague) {
  //     maxListLength = 2;
  //   } else if (maxListLength < 4) {
  //     maxListLength = 4;
  //   }

  //   const realList = new Array(maxListLength).fill(0);
  //   const getRoundScore = (v, i) => {
  //     let defVal = '-';
  //     if (+currentRound === i && status !== 1) defVal = 0;

  //     return v || defVal;
  //   };

  //   return {
  //     homeTeamRoundsList: realList.map((row, index) => getRoundScore(homeListFlag[index], index)),
  //     awayTeamRoundsList: realList.map((row, index) => getRoundScore(awayListFlag[index], index)),
  //   };
  // }, [score, isBasketball, currentRound, status]);

  // -------------- 新逻辑
  const matchStatus = useMemo(() => ({
    [enumBallType.football]: enumFootballMatchStatus, // 足球
    [enumBallType.basketball]: enumBasketballMatchStatus, // 篮球
  }[matchType] || {}), [matchType]);

  const footballShowTimeStatus = [2, 4, 5, 6, 7]; // 足球展示时间的状态
  const basketballShowTimeStatus = [2, 4, 6, 8, 9]; // 篮球展示时间的状态
  // 是否展示比赛时间 进行中的需要
  const showMatchTime = useMemo(() => {
    const showTimeStatus = {
      [enumBallType.football]: footballShowTimeStatus, // 足球展示时间的状态
      [enumBallType.basketball]: basketballShowTimeStatus, // 篮球展示时间的状态
    }[matchType] || [];
    return showTimeStatus.includes(status);
  }, [matchType, status]);
  // 比赛时间格式化
  const formatMatchTime = useMemo(() => {
    if (!showMatchTime) return '';
    return ({
      [enumBallType.football]: () => {
        // new - teeTime
        const secondHalfStatus = 4;
        const second = Math.floor(+new Date() / 1000 - teeTime);
        if (second > 0) {
          const minute = Math.floor(second / 60);
          const secondHalf = minute + (status === secondHalfStatus ? 45 : 0); // 下半场要加45
          return (
            <>
              {secondHalf > 90 ? '90+' : secondHalf}
              <span className={styles.statusAni}>’</span>
            </>
          );
        }
        return null;
      },
      [enumBallType.basketball]: () => {
        const second = Math.floor(+surplusTime / 60) || 0;
        const minute = +surplusTime % 60 || 0;
        if (second || minute) {
          return `${paddingZero(second)}:${paddingZero(minute)}`;
        }
        return null;
      },
    }[matchType] || empty)() || null;
  }, [matchType, status, teeTime, surplusTime, showMatchTime]);

  const footballShowScoreStatus = [2, 3, 4, 5, 6, 7, 8]; // 足球展示比分的状态
  const basketballShowScoreStatus = [2, 3, 4, 5, 6, 7, 8, 9, 10]; // 篮球展示比分的状态
  // 是否展示比分
  const showScore = useMemo(() => {
    const showScoreStatus = {
      [enumBallType.football]: footballShowScoreStatus, // 足球展示比分的状态
      [enumBallType.basketball]: basketballShowScoreStatus, // 篮球展示比分的状态
    }[matchType] || [];
    return showScoreStatus.includes(status);
  }, [matchType, status]);
  // 比分计算 篮球需要累加
  const calScore = useCallback((v) => (Array.isArray(v) ? add(...v) : v) || 0, []);
  const getScoreHandle = useCallback((v) => {
    if (!showScore) return '-';
    return calScore(v);
  }, []);

  return (
    <div className={styles.container}>
      <div className={styles.head}>
        <div className={styles.headTime}>
          <RenderJudge
            value={startTime}
            active={dayJs(startTime).format('HH:mm')}
          />
        </div>
        <div className={styles.headLeague}>{eventName}</div>
        <div className={ClassNames(styles.headStatus, { [styles.isDisable]: status === 1 })}>
          {!isFootball && <span>{matchStatus[status]}</span>}
          <RenderJudge
            value={showMatchTime}
            active={(
              <span className={ClassNames(styles.headStatus, styles.statusAni)}>{formatMatchTime}</span>
            )}
            inactive={isFootball && <span>{matchStatus[status]}</span>}
          />
        </div>
      </div>
      <div className={styles.content}>
        <div className={ClassNames(styles.inner, { [styles.isReverse]: isBasketball })}>
          <div className={styles.teamWrapper}>
            <Image
              className={styles.teamImage}
              src={homeTeamLogo}
              defaultImage={defaultMatchImage}
              alt={homeTeamName}
            />
            <div className={styles.teamName}>{homeTeamName}</div>
            <RenderJudge
              value={isFootball}
              active={(
                <div className={styles.brandWrapper}>
                  <RenderJudge
                    value={homeTeamRed}
                    active={(
                      <div className={ClassNames(styles.boardItem, styles.isRed)}>{homeTeamRed}</div>
                    )}
                  />
                  <RenderJudge
                    value={homeTeamYellow}
                    active={(
                      <div className={ClassNames(styles.boardItem, styles.isYellow)}>{homeTeamYellow}</div>
                    )}
                  />
                </div>
              )}
            />
            <RenderJudge
              value={isBasketball}
              active={(
                <div className={styles.roundsWrapper}>
                  {Array.isArray(homeTeamScore) && (homeTeamScore || []).map((row, index) => (
                    <div className={styles.roundItem} key={index}>{row}</div>
                  ))}
                </div>
              )}
            />
            <div
              className={ClassNames(styles.teamScore, { [styles.isShowPoint]: visibleScorePoint.home })}
            >
              {getScoreHandle(homeTeamScore)}
            </div>
          </div>
          <div className={styles.teamWrapper}>
            <Image
              className={styles.teamImage}
              src={awayTeamLogo}
              defaultImage={defaultMatchImage}
              alt={awayTeamName}
            />
            <div className={styles.teamName}>{awayTeamName}</div>
            <RenderJudge
              value={isFootball}
              active={(
                <div className={styles.brandWrapper}>
                  <RenderJudge
                    value={awayTeamRed}
                    active={(
                      <div className={ClassNames(styles.boardItem, styles.isRed)}>{awayTeamRed}</div>
                    )}
                  />
                  <RenderJudge
                    value={awayTeamYellow}
                    active={(
                      <div className={ClassNames(styles.boardItem, styles.isYellow)}>{awayTeamYellow}</div>
                    )}
                  />
                </div>
              )}
            />
            <RenderJudge
              value={isBasketball}
              active={(
                <div className={styles.roundsWrapper}>
                  {Array.isArray(awayTeamScore) && (awayTeamScore || []).map((row, index) => (
                    <div className={styles.roundItem} key={index}>{row}</div>
                  ))}
                </div>
              )}
            />
            <div
              className={ClassNames(styles.teamScore, { [styles.isShowPoint]: visibleScorePoint.away })}
            >
              {getScoreHandle(awayTeamScore)}
            </div>
          </div>
        </div>
        <div className={ClassNames(styles.liveList, preList?.length ? '' : styles.notLive)}>
          <RenderJudge
            value={preList?.length}
            active={(preList || []).slice(0, 5).map((row, index) => (
              <Link className={styles.liveItem} to={`/live/room/${row.roomId}`} key={index}>
                <Image
                  className={styles.liveImage}
                  src={row.headImg}
                  defaultImage={DefaultUserImage}
                  alt={row.nickname}
                />
                <RenderJudge
                  value={isLive === 1}
                  active={(
                    <div className={styles.anchorStatus}>
                      <PlayLoading
                        align="bottom"
                        color="#fff"
                        width={6}
                        height={8}
                        number={3}
                        itemWidth={2}
                        itemMinHeight={4}
                      />
                    </div>
                  )}
                />
              </Link>
            ))}
            inactive="暂无直播"
          />
        </div>
      </div>
    </div>
  );
};

ScoreRow.defaultProps = {
  data: {},
};

export default ScoreRow;
